package com.book.bookmanager.service;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.bookmanager.mapper.UserMapper;
import com.book.bookmanager.mapper.UserRoleMapper;
import com.book.bookmanager.pojo.Menu;
import com.book.bookmanager.pojo.RoleMenu;
import com.book.bookmanager.pojo.User;
import com.book.bookmanager.pojo.UserRole;
import com.book.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class userServiceImpl extends ServiceImpl<UserMapper, User> implements userService {
    @Autowired
    private UserMapper ud;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Autowired
    private menuService ms;
    @Override
    public Map<String, Object> login(User user) {
        //查询用户名,根据用户名查询密码
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, user.getUserName());
        User loginUser = this.baseMapper.selectOne(wrapper);
//        User loginUser = ud.queryByUser(user.getUser());
        //结果不为空，生成token，存入redis
        if (loginUser != null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())) {
            //uuid
            String key = "user:" + UUID.randomUUID();

            //存入redis
            loginUser.setPassword(null);
            redisTemplate.opsForValue().set(key, loginUser, 10, TimeUnit.MINUTES);

            //返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", key);
            return data;
        }


        return null;
    }

//    @Override
//    public Map<String, Object> login(User user) {
//        //查询用户名密码
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(User::getUserName, user.getUserName());
//        wrapper.eq(User::getPassword, user.getPassword());
//        User loginUser = this.baseMapper.selectOne(wrapper);
////        User loginUser = ud.queryByUser(user.getUser());
//        //结果不为空，生成token，存入redis
//        if (loginUser != null) {
//            //uuid
//            String key = "user:" + UUID.randomUUID();
//
//            //存入redis
//            loginUser.setPassword(null);
//            redisTemplate.opsForValue().set(key, loginUser, 10, TimeUnit.MINUTES);
//
//            //返回数据
//            Map<String, Object> data = new HashMap<>();
//            data.put("token", key);
//            return data;
//        }
//
//
//        return null;
//    }

    @Override
    public List<User> queryAll() {
        return ud.queryAll();
    }

    @Override
    public void add(User user) {
         ud.add(user);
    }

    @Override
    public User queryByUser(String userName) {
        User user = this.baseMapper.queryByUser(userName);
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserName,userName);
        List<UserRole> userRoleList = userRoleMapper.selectRoleList(wrapper);
        List<Integer> roleIdList = userRoleList.stream()
                .map(userRole -> {return userRole.getRole_id();})
                .collect(Collectors.toList());
        user.setRoleIdList(roleIdList);

        return user;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        //从redis获取信息
        Object obj = redisTemplate.opsForValue().get(token);
        if (obj != null) {
            User loginUser = JSON.parseObject(JSON.toJSONString(obj), User.class);
            Map<String, Object> data = new HashMap<>();
            data.put("name", loginUser.getUserName());
            //角色
            List<String> roleList = this.baseMapper.getRoleByUserName(loginUser.getUserName());
            data.put("roles", roleList);

            //获取权限列表

            List<Menu> menuList = ms.getMenuListByUserName(loginUser.getUserName());
            data.put("menuList",menuList);
            return data;
        }
        return null;
    }

    @Override
    public void loginOut(String token) {
        redisTemplate.delete(token);
    }

    @Override
    public Map<String, Object> register(User user) {

        //查询用户名,根据用户名查询密码
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, user.getUserName());
        User loginUser = this.baseMapper.selectOne(wrapper);
        String username = user.getUserName();
//        User loginUser = ud.queryByUser(user.getUser());
        //结果不为空，并 且不等于任何其他用户名，填加信息
        if (loginUser == null && username != null) {
            //添加数据到数据库

            user.setPassword(passwordEncoder.encode(user.getPassword()));
            add(user);
            //返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("userName",username);
            data.put("password",user.getPassword());
            return data;
        }


        return null;
    }

    @Override
    public User removeByUser(String name) {
        //清除用户
        this.baseMapper.remove(name);
        //清除角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserName,name);
        userRoleMapper.delete(wrapper);
        return null;
    }

    @Override
    public void addUser(User user) {
        //写入角色表
        this.baseMapper.add(user);

        //写入用户角色表

        List<Integer> roleIdList = user.getRoleIdList();
        if(null != roleIdList){
            for(Integer roleId:roleIdList){
                userRoleMapper.insertUserRole(new UserRole(null,user.getUserName(),roleId,null));
            }

        }
    }

    @Override
    public void updateUserById(User user) {

        //修改User表
        this.baseMapper.updateByUserName(user);

        //删除user_role表
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserName,user.getUserName());
        userRoleMapper.delete(wrapper);

        //新增user_role表
        if(null != user.getUserName()){
            for (Integer roleId: user.getRoleIdList()){
                userRoleMapper.insertUserRole(new UserRole(null, user.getUserName(),roleId,null));
            }
        }
    }

}
